/*
 * Copyright 2008 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package bw.net;

import com.sshtools.j2ssh.*;
import com.sshtools.j2ssh.authentication.*;
import com.sshtools.j2ssh.sftp.*;
import com.sshtools.j2ssh.transport.*;
import java.io.*;
import bw.util.*;

public class SimpleSFTPClient
{
    public static final int SSH_CLIENT_TIMEOUT = 30000;

    private String _host = null;
    private String _username = null;
    private String _password = null;
    private SshClient _ssh = null;
    private SftpClient _client = null;

    public SimpleSFTPClient ( String host, String username, String password )
    {
        _host = host;
        _username = username;
        _password = password;
    }

    public void put ( InputStream stream, String remotePath ) throws IOException
    {
        if ( _ssh == null || !_ssh.isConnected() )
        {
            connectSshClient();
        }

        if ( _client != null )
        {
            _client.put( stream, remotePath );
            //Log.getInstance().write( "SFTP: Put file to: " + remotePath );
        }
    }

    public void rm ( String remotePath ) throws IOException
    {
        if ( _ssh == null || !_ssh.isConnected() )
        {
            connectSshClient();
        }

        if ( _client != null )
        {
            _client.rm( remotePath );
        }
    }

    private void connectSshClient () throws IOException
    {
        if ( _ssh == null )
        {
            _ssh = new SshClient();
            _ssh.setSocketTimeout( SSH_CLIENT_TIMEOUT );
            _ssh.addEventHandler( new SFTPEventHandler() );
        }

        //REVISIT -- Should probably do something better with host key verification
        //Log.getInstance().write( "SFTP: Connecting ..." );
        _ssh.connect( _host, new IgnoreHostKeyVerification() );
        
        PasswordAuthenticationClient passwordAuthClient = new PasswordAuthenticationClient();
        passwordAuthClient.setUsername( _username );
        passwordAuthClient.setPassword( _password );
        int result = _ssh.authenticate( passwordAuthClient );
        
        if ( result != AuthenticationProtocolState.COMPLETE )
        {
            Log.getInstance().write( "SFTP Login to " + _username + "@" + _host + " failed" );
        }
        else
        {
            _client = _ssh.openSftpClient();
        }

        //Log.getInstance().write( "SFTP: Connection established." );
    }

    class SFTPEventHandler extends SshEventAdapter
    {
        public void onSocketTimeout ( TransportProtocol transport ) 
        {
            //Log.getInstance().write( "SFTP: Connection inactive for 30 seconds. Closing." );
            try
            {
                _client.quit();
                _client = null;
                _ssh.disconnect();
                _ssh = null;
                //Log.getInstance().write( "SFTP: Connection closed" );
            }
            catch ( IOException ex )
            {
                Log.getInstance().write( "SFTPClient: Problem on socket timeout!", ex );
            }
        }
    }

    public static void main ( String [] args )
    {
        String host = args[0];
        String username = args[1];
        String password = args[2];
        String filePath = args[3];

        try
        {
            HostKeyVerification ignore = new IgnoreHostKeyVerification();

            SshClient ssh = new SshClient();
            ssh.connect( host, ignore );
            
            //Authenticate
            PasswordAuthenticationClient passwordAuthClient = new PasswordAuthenticationClient();
            passwordAuthClient.setUsername( username );
            passwordAuthClient.setPassword( password );
            int result = ssh.authenticate( passwordAuthClient );
            
            if ( result != AuthenticationProtocolState.COMPLETE )
            {
                System.out.println( "Login to " + host + ":" + " " + 
                                    username + "/" + password + " failed" );
            }
            
            //Open the SFTP channel
            SftpClient client = ssh.openSftpClient();
            
            //Send the file
            client.put(filePath, "/afs/nd.edu/user13/jwatkin2/test.txt");
            
            //disconnect
            client.quit();
            ssh.disconnect();
        }
        catch ( IOException ex )
        {
            ex.printStackTrace();
        }
    }
}